package com.whk0710.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.whk0710.dao.UsersDao;
import com.whk0710.entity.Users;
import com.whk0710.util.DBUtil;

/**
 * @author whk0710
 * */
public class UsersDaoImpl implements UsersDao {

	/**
	 * @return
	 * @param userName
	 * @param password
	 * */
	@Override
	public Users login(String userName, String password) {
		DBUtil util = new DBUtil();
		Connection conn = util.openConnection();
		String sql = "select * from users where userName= '" + userName
				+ "' and password='" + password + "'";
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {

				Users u = new Users();
				int id = rs.getInt("id");
				u.setId(id);
				u.setUserName(userName);
				return u;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			util.closeConn(conn);
		}
		return null;
	}

	/**
	 * @return
	 * @param userName
	 * @param password
	 * @param phone
	 * @param address
	 * @param rname
	 * */
	@Override
	public String register(String userName, String password, String phone,
			String address, String rname) {
		// TODO Auto-generated method stub
		String sql2 = "select count(*) from users where username='" + userName
				+ "'";
		String sql = "insert into users(username,password,phone,address,rname) values('"
				+ userName
				+ "','"
				+ password
				+ "','"
				+ address
				+ "','"
				+ phone
				+ "','" + rname + "')";
		DBUtil util = new DBUtil();
		Connection conn = util.openConnection();
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql2);
			ResultSet rs = pstmt.executeQuery();
			int count = 0;
			while (rs.next()) {
				count = rs.getInt(1);
			}
			if (count != 0) {
				return "2";
			} else {
				Statement stmt = conn.createStatement();
				stmt.executeUpdate(sql);
				return "1";
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "2";
		} finally {
			util.closeConn(conn);
		}
	}

}